import 'package:flutter/material.dart';

class LoadImageView extends StatefulWidget {
  final String imageUrl;
  final String defImagPath;
  final double width;
  final double height;
  final BoxFit fit;

  LoadImageView({
    @required this.imageUrl,
    this.width,
    this.height,
    this.fit,
    this.defImagPath = "images/icon_loading.png",
  });

  @override
  _LoadImageViewState createState() => _LoadImageViewState();
}

class _LoadImageViewState extends State<LoadImageView> {
  Image _image;
  @override
  void initState() {
    super.initState();
    _image = Image.network(
      widget.imageUrl,
      width: widget.width,
      height: widget.height,
      fit: widget.fit,
    );
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(
      ImageStreamListener((_, __) {
        //加载成功
      }, onError: (dynamic exception, StackTrace stackTrace) {
        setState(() {
          _image = Image.asset(
            widget.defImagPath,
            width: widget.width,
            height: widget.height,
            fit: widget.fit,
          );
        });
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: _image,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/icon_loading.png"),
        ),
      ),
    );
  }
}
